package com.benson.common.swagger.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.benson.common.swagger.entity.ResultPoJo;
import com.benson.common.swagger.entity.SwaggerUiConfig;
import com.benson.common.swagger.service.ISwaggerAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Swagger 登录管理
 *
 * @author zhangby
 * @date 19/2/20 5:03 pm
 */
@RestController
@RequestMapping("/swagger")
public class SwaggerAuthController {

    private static final String SWAGGER_USER = "SWAGGER_USER";

    /**
     * port
     */
    @Value("${server.port:8080}")
    private String host;

    @Autowired
    SwaggerUiConfig swaggerUiConfig;

    @Autowired
    ISwaggerAuthService swaggerAuthService;

    /**
     * Verify that the login is invalid
     *
     * @return []
     */
    @GetMapping("/login/verify")
    public ResultPoJo verifyLogin(HttpServletRequest request) {
        List<String> rsList = new ArrayList<>();
        Object user = request.getSession().getAttribute(SWAGGER_USER);
        // 如果未设置用户名密码，默认不跳转登录
        if (user != null || swaggerUiConfig.getUsername() == null
                || "".equals(swaggerUiConfig.getUsername().trim())) {
            rsList.add("admin");
        }
        return ResultPoJo.ok(rsList);
    }

    /**
     * login
     *
     * @param username 用户名
     * @param password 密码
     * @return User
     */
    @GetMapping("/login")
    public ResultPoJo login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request
    ) {
        ResultPoJo resultPoJo = ResultPoJo.ok();
        /** 参数验证 */
        if (username == null || "".equals(username.trim())) {
            return resultPoJo.setCode("999").setMsg("用户名不能为空");
        }
        if (password == null || "".equals(password.trim())) {
            return resultPoJo.setCode("999").setMsg("密码不能为空");
        }
        if (!username.equals(swaggerUiConfig.getUsername())) {
            return resultPoJo.setCode("999").setMsg("用户名不存在");
        }
        if (!password.equals(swaggerUiConfig.getPassword())) {
            return resultPoJo.setCode("999").setMsg("密码错误");
        }
        //登录成功
        request.getSession().setAttribute(SWAGGER_USER, swaggerUiConfig);
        return resultPoJo;
    }

    /**
     * logout
     *
     * @return
     */
    @GetMapping("/logout")
    public ResultPoJo logout(HttpServletRequest request) {
        /** 退出登录 */
        request.getSession().removeAttribute(SWAGGER_USER);
        return ResultPoJo.ok();
    }

    /**
     * 获取Swagger 资源
     *
     * @return
     */
    @GetMapping("/resources/get")
    public List<Dict> getSwaggerResources(HttpServletRequest request) {
        List<Dict> rsList = new ArrayList<>();
        Object user = request.getSession().getAttribute(SWAGGER_USER);

        // 如果未设置用户名密码，默认不跳转登录
        if (user != null || swaggerUiConfig.getUsername() == null
                || "".equals(swaggerUiConfig.getUsername().trim())
                || swaggerAuthService.verifyToken(request)
        ) {
            // /swagger-resources
            String visitUrl = "http://localhost:" + host;
//            String visitUrl = "/";
            if (StrUtil.isNotBlank(swaggerUiConfig.getVisitUrl())) {
                visitUrl = swaggerUiConfig.getVisitUrl();
            }
            String json = HttpUtil.get(visitUrl + "/swagger-resources");
//            String seeUrl = visitUrl;
            rsList = JSONUtil.parseArray(json).toList(Dict.class)
                    .stream()
                    .map(dict -> {
                        String[] dictStr = dict.getStr("url").split("\\?");
                        AES aes = SecureUtil.aes("Bacisic_Swagger_".getBytes());
                        String url = dict.getStr("url") + (dict.getStr("url").contains("?") ? "&" : "?") + "sign=" + aes.encryptHex(dictStr[0]);
                        return Dict.create()
                                .set("name", dict.getStr("name"))
                                .set("url",  url);
                    })
                    .collect(Collectors.toList());
        }
        return rsList;
    }
}
